import traceback

from mapper import DemoMapper
from model.DemoInDTO import DemoInDTO
from model.DemoOutDTO import DemoOutDTO
from driver import db
from config import logger


def demo_select_simplest():
    the_list: list = db.execute(DemoMapper.demo_sql_simplest)
    return the_list


def demo_select_get_one():
    obj: DemoOutDTO = db.get_one(DemoMapper.demo_sql_simplest, DemoOutDTO)
    return obj


def demo_select_get_list():
    obj_list: list[DemoOutDTO] = db.get_list(DemoMapper.demo_sql_simplest, DemoOutDTO)
    return obj_list


def demo_select_has_params():
    demoInDTO = DemoInDTO(0, 2)
    params: tuple = (demoInDTO.del_flag, demoInDTO.level)
    obj_list: list[DemoOutDTO] = db.get_list(DemoMapper.demo_sql_has_params, DemoOutDTO, params)
    return obj_list


def demo_insert_one():
    params: tuple = (db.get_id(), "这是一条测试数据")
    row_count: int = db.insert_one(DemoMapper.demo_insert, params)
    return row_count


"""
    显式提交事务
"""


def demo_explicitly_transaction():
    params_1: tuple = (db.get_id(), "显示提交事务测试1")
    params_2: tuple = (db.get_id(), "显示提交事务测试2")
    '''
        务必用try/except/finally包裹事务逻辑
    '''
    try:
        # 必须先开启事务
        db.open_transaction()

        ### 逻辑
        row_count: int = 0
        row_count += db.insert_one(DemoMapper.demo_insert, params_1)
        # raise Exception("手动抛出异常，模拟出现错误的场景，导致事务回滚")
        row_count += db.insert_one(DemoMapper.demo_insert, params_2)

        # 不要忘了逻辑的最后提交事务
        db.commit()
    # 必须使用Exception进行异常抓捕
    except Exception as e:
        traceback.print_exc()
    finally:
        # 必须在finally中终止事务，否则会导致事务无法关闭，所有删改操作全部失效
        db.close_transaction()
    return row_count


@db.transactional()
def demo_decorators_transaction():
    params_1: tuple = (db.get_id(), "装饰器式提交事务测试1")
    params_2: tuple = (db.get_id(), "装饰器式示提交事务测试2")

    row_count: int = 0
    row_count += db.insert_one(DemoMapper.demo_insert, params_1)
    # raise Exception("手动抛出异常，模拟出现错误的场景，导致事务回滚")
    row_count += db.insert_one(DemoMapper.demo_insert, params_2)

    return row_count
